// HTTP 请求工具

import type { ApiResponse } from '../types/auth';

// 基础配置
const BASE_URL = '/api';

// 请求配置接口
interface RequestConfig {
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  headers?: Record<string, string>;
  body?: any;
}

// HTTP 请求类
class HttpClient {
  private baseURL: string;

  constructor(baseURL: string = BASE_URL) {
    this.baseURL = baseURL;
  }

  // 通用请求方法
  private async request<T = any>(
    endpoint: string,
    config: RequestConfig = {}
  ): Promise<ApiResponse<T>> {
    const { method = 'GET', headers = {}, body } = config;
    
    const url = `${this.baseURL}${endpoint}`;
    
    const requestHeaders: Record<string, string> = {
      'Content-Type': 'application/json',
      ...headers,
    };

    // 从localStorage获取token
    const token = localStorage.getItem('accessToken');
    if (token) {
      requestHeaders.Authorization = `Bearer ${token}`;
    }

    try {
      const response = await fetch(url, {
        method,
        headers: requestHeaders,
        body: body ? JSON.stringify(body) : undefined,
      });

      // 处理401未授权错误
      if (response.status === 401) {
        // 在生产环境中才清除token和重定向
        if (!import.meta.env.DEV) {
          // 清除过期的token和用户信息
          localStorage.removeItem('accessToken');
          localStorage.removeItem('userInfo');
          
          // 重定向到登录页面
          window.location.href = '/login';
        }
        
        // 抛出401错误
        const errorData = await response.json().catch(() => ({
          code: 401,
          message: '登录已过期，请重新登录',
          data: null,
          timestamp: new Date().toISOString()
        }));
        throw new Error(JSON.stringify(errorData));
      }

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({
          code: response.status,
          message: `HTTP error! status: ${response.status}`,
          data: null,
          timestamp: new Date().toISOString()
        }));
        throw new Error(JSON.stringify(errorData));
      }

      const data = await response.json();
      return data;
    } catch (error) {
      console.error('Request failed:', error);
      throw error;
    }
  }

  // GET 请求
  async get<T = any>(endpoint: string, headers?: Record<string, string>): Promise<ApiResponse<T>> {
    return this.request<T>(endpoint, { method: 'GET', headers });
  }

  // POST 请求
  async post<T = any>(
    endpoint: string,
    body?: any,
    headers?: Record<string, string>
  ): Promise<ApiResponse<T>> {
    return this.request<T>(endpoint, { method: 'POST', body, headers });
  }

  // PUT 请求
  async put<T = any>(
    endpoint: string,
    body?: any,
    headers?: Record<string, string>
  ): Promise<ApiResponse<T>> {
    return this.request<T>(endpoint, { method: 'PUT', body, headers });
  }

  // DELETE 请求
  async delete<T = any>(endpoint: string, headers?: Record<string, string>): Promise<ApiResponse<T>> {
    return this.request<T>(endpoint, { method: 'DELETE', headers });
  }
}

// 导出HTTP客户端实例
export const http = new HttpClient();

// 导出默认实例
export default http;